package com.htjx.mall.controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.htjx.mall.commons.api.Result;
import com.htjx.mall.commons.models.User;
import com.htjx.mall.commons.utils.Checks;
import com.htjx.mall.controllers.commonapi.AuthorizeList;
import com.htjx.mall.controllers.commonapi.Constant;
import com.htjx.mall.services.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private ShaPasswordEncoder passwordEncoder;
	/****
	 * 用户登录
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result login(String phone, String password, HttpServletRequest request, HttpServletResponse response) {
		if (StringUtils.isBlank(phone)) {
			return new Result(9,"手机不能为空");
		}
		
		if(!Checks.isMobileNO(phone)) {
			return new Result(9, "请输入正确的手机号码");
		}
		
		if (StringUtils.isBlank(password)) {
			return new Result(9,"密码不能为空");
		}
		
		User user = userService.findUniqueBy("phone", phone);
		if (user == null) {
			return new Result(9, "手机号或密码不正确");
		}

		String encodePassword = passwordEncoder.encodePassword(password, null);
		if (!user.getPassword().equals(encodePassword)) {
			return new Result(9, "手机号或密码有误");
		}
		
		String token = AuthorizeList.setCurrentAuthUser(user, response);

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("token", token);
		
		Result result = new Result(0, "登录成功");
		result.setBody(retMap);
		return result;
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result reg(User user, String re_password, HttpServletResponse response) {
		String phone = user.getPhone();
		if (StringUtils.isBlank(phone)) {
			return new Result(9, "手机号不能为空");
		}
		
		if(!Checks.isMobileNO(phone)) {
			return new Result(9, "请输入正确的手机号码");
		}
		
		if(userService.checkUniqueByProperty("phone", phone)) {
			return new Result(9, "该手机号已被注册");
		}
		
		String password = user.getPassword();
		if(StringUtils.isBlank(password)) {
			return new Result(9, "密码不能为空");
		}
		
		if (!Checks.isPassword(password) || password.length() < 6 || password.length() > 20) {
			return new Result(9, "请输入6~20位密码，建议使用字母和数字混合的密码");
		}
		
		if (!password.equals(re_password)) {
			return new Result(9, "两次密码不一致");
		}
		
		user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
		user.setUser_name(user.getPhone());
		user.setRegister_time(new Date());
		user.setActive(true);
		userService.insertOne(user);
		
		user = userService.findUniqueBy("phone", user.getPhone());
		String token = AuthorizeList.setCurrentAuthUser(user, response);

		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("token", token);
		
		Result result = new Result(0, "注册成功");
		result.setBody(retMap);
		return result;
	}
	/****
	 * 安全退出
	 */
	@RequestMapping(value = "/quit", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result login(HttpServletRequest request, HttpServletResponse response) {
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user != null) {
			Cookie cookie = WebUtils.getCookie(request, Constant.TOKEN_NAME);
			cookie.setValue(null);
			cookie.setMaxAge(0);
			cookie.setPath("/");
			response.addCookie(cookie);
		}
		Result result = new Result(0, "安全退出");
		return result;
	}
	
	/**获取登录状态**/
	@RequestMapping(value = "/state", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public Result state(HttpServletRequest request) {
		boolean state = false;
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user != null) {
			state = true;
		}
		Result result = new Result(0, "安全退出");
		result.setBody(state);
		return result;
	}
	
	/**获取登录状态**/
	@RequestMapping(value = "/repassword", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result repassword(@RequestParam String old_password, @RequestParam String new_password, @RequestParam String re_password, HttpServletRequest request) {
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user == null) {
			return new Result(9,"请重新登录");
		}
		
		if(StringUtils.isBlank(old_password)) {
			return new Result(9, "请输入旧密码");
		}
		
		if(StringUtils.isBlank(new_password)) {
			return new Result(9, "请输入新密码");
		}
		
		if(StringUtils.isBlank(re_password)) {
			return new Result(9, "请重复输入新密码");
		}
		
		if(! user.getPassword().equals(passwordEncoder.encodePassword(old_password, null))) {
			return new Result(9, "旧密码不匹配，请再次尝试");
		}
		
		if (!Checks.isPassword(new_password)) {
			return new Result(9, "请至少输入6位密码，建议使用字母和数字混合的密码");
		}
		
		if (!new_password.equals(re_password)) {
			return new Result(9, "两次输入的新密码不一致，请再次输入");
		}
		
		user.setPassword(passwordEncoder.encodePassword(new_password, null));
		
		userService.updateOne(user);
		
		Result result = new Result(0, "密码修改成功。");
		return result;
	}
	
}
